package com.weixin.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.ConnectException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.weixin.po.ImageMessage;
import com.weixin.po.Music;
import com.weixin.po.MusicMessage;
import com.weixin.po.News;
import com.weixin.po.NewsMessage;
import com.weixin.po.TextMessage;


/**
 * 锟斤拷息锟斤拷装锟斤�?
 * @author Stephen
 *
 */
public class MessageUtil {	
	
	public static final String MESSAGE_TEXT = "text";
	public static final String MESSAGE_NEWS = "news";
	public static final String MESSAGE_IMAGE = "image";
	public static final String MESSAGE_VOICE = "voice";
	public static final String MESSAGE_MUSIC = "music";
	public static final String MESSAGE_VIDEO = "video";
	public static final String MESSAGE_LINK = "link";
	public static final String MESSAGE_LOCATION = "location";
	public static final String MESSAGE_EVNET = "event";
	public static final String MESSAGE_SUBSCRIBE = "subscribe";
	public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
	public static final String MESSAGE_CLICK = "CLICK";
	public static final String MESSAGE_VIEW = "VIEW";
	public static final String MESSAGE_SCANCODE= "scancode_push";
	
	/**
	 * xml转为map锟斤拷锟斤拷
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		
		Element root = doc.getRootElement();
		
		List<Element> list = root.elements();
		
		for(Element e : list){
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}
	
	/**
	 * 锟斤拷锟侥憋拷锟斤拷息锟斤拷锟斤拷转为xml
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessage textMessage){
//		XStream xstream = new XStream();
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	
	/**
	 * 锟斤拷装锟侥憋拷锟斤拷息
	 * @param toUserName
	 * @param fromUserName
	 * @param content
	 * @return
	 */
	public static String initText(String toUserName,String fromUserName,String content){
		TextMessage text = new TextMessage();
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType(MessageUtil.MESSAGE_TEXT);
		text.setCreateTime(new Date().getTime());
		text.setContent(content);
		return textMessageToXml(text);
	}
	
	
	public static String initText1(String toUserName,String fromUserName,String content){
		TextMessage text = new TextMessage();
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType(MessageUtil.MESSAGE_TEXT);
		text.setCreateTime(new Date().getTime());
		text.setContent("http://czw.tunnel.qydev.com/FenXiao/pages/weixin/index.jsp");
		return textMessageToXml(text);
	}
	
	/**
	 * 锟斤拷锟剿碉�?
	 * @return
	 */
	public static String menuText(){
		StringBuffer sb = new StringBuffer();
		sb.append("静夜思 李白\n");
		sb.append("床前明月光\n");
		sb.append("疑是地上霜\n");
		sb.append("举头望明月\n");
		sb.append("低头思故乡\n");
		
		return sb.toString();
	}
	
	public static String menuText1(){
		StringBuffer sb = new StringBuffer();
		sb.append("欢迎关注社区公众号");
		/*sb.append("床前明月光\n");
		sb.append("1疑是地上霜\n");
		sb.append("2举头望明月\n");
		sb.append("3低头思故乡\n");*/
		
		return sb.toString();
	}
	
	public static String firstMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("恭喜您已完成本次公众号关注任务 ！！");
//        sb.append("时维九月，序属三秋。潦水尽而寒潭清，烟光凝而暮山紫。俨骖騑于上路，访风景于崇阿。临帝子之长洲，得仙人之旧馆。层台耸翠，上出重霄；飞阁流丹，下临无地。鹤汀凫渚，穷岛屿之萦回；桂殿兰宫，列冈峦之体势");
		return sb.toString();
	}
	
	public static String first1Menu(){
		StringBuffer sb = new StringBuffer();
		sb.append("很抱歉，该任务已完成，您本次发送无效 ！！");
//        sb.append("时维九月，序属三秋。潦水尽而寒潭清，烟光凝而暮山紫。俨骖騑于上路，访风景于崇阿。临帝子之长洲，得仙人之旧馆。层台耸翠，上出重霄；飞阁流丹，下临无地。鹤汀凫渚，穷岛屿之萦回；桂殿兰宫，列冈峦之体势");
		return sb.toString();
	}
	
	public static String first2Menu(){
		StringBuffer sb = new StringBuffer();
		sb.append("很抱歉，该任务已结束，您本次发送无效 ！！");
//        sb.append("时维九月，序属三秋。潦水尽而寒潭清，烟光凝而暮山紫。俨骖騑于上路，访风景于崇阿。临帝子之长洲，得仙人之旧馆。层台耸翠，上出重霄；飞阁流丹，下临无地。鹤汀凫渚，穷岛屿之萦回；桂殿兰宫，列冈峦之体势");
		return sb.toString();
	}
	public static String first3Menu(){
		StringBuffer sb = new StringBuffer();
		sb.append("该任务您已完成，您本次发送无效 ！！");
//        sb.append("时维九月，序属三秋。潦水尽而寒潭清，烟光凝而暮山紫。俨骖騑于上路，访风景于崇阿。临帝子之长洲，得仙人之旧馆。层台耸翠，上出重霄；飞阁流丹，下临无地。鹤汀凫渚，穷岛屿之萦回；桂殿兰宫，列冈峦之体势");
		return sb.toString();
	}
	
	public static String secondMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("您输入的随机码不对 ！");
//		sb.append("若夫淫雨霏霏，连月不开，阴风怒号，浊浪排空；日星隐曜，山岳潜形；商旅不行，樯倾楫摧；薄暮冥冥，虎啸猿啼。登斯楼也，则有去国怀乡，忧谗畏讥，满目萧然，感极而悲者矣");
//		sb.append("至若春和景明，波澜不惊，上下天光，一碧万顷；沙鸥翔集，锦鳞游泳；岸芷汀兰，郁郁青青。而或长烟一空，皓月千里，浮光跃金，静影沉璧，渔歌互答，此乐何极！登斯楼也，则有心旷神怡，宠辱偕忘，把酒临风，其喜洋洋者矣。");
		return sb.toString();
	}
	
	public static String threeMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("环滁皆山也。其西南诸峰，林壑尤美，望之蔚然而深秀者，琅琊也\n\n");
		sb.append("山行六七里，渐闻水声潺潺而泻出于两峰之间者，酿泉也\n");
		sb.append("峰回路转，有亭翼然临于泉上者，醉翁亭也\n");
		sb.append("作亭者谁？山之僧智仙也\n");
		sb.append("名之者谁？太守自谓也\n\n");
		sb.append("太守与客来饮于此，饮少辄醉，而年又最高，故自号曰醉翁也");
		return sb.toString();
	}
	/**
	 * 图锟斤拷锟斤拷息转为xml
	 * @param newsMessage
	 * @return
	 */
	public static String newsMessageToXml(NewsMessage newsMessage){
//		XStream xstream = new XStream();
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new News().getClass());
		return xstream.toXML(newsMessage);
	}
	
	/**
	 * 图片锟斤拷息转为xml
	 * @param imageMessage
	 * @return
	 */
	public static String imageMessageToXml(ImageMessage imageMessage){
	/*	XStream xstream = new XStream();*/
		xstream.alias("xml", imageMessage.getClass());
		return xstream.toXML(imageMessage);
	}
	
	
	private static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点都增加CDATA标记
				boolean cdata = true;

				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
	
	/**
	 * 锟斤拷锟斤拷锟斤拷息转为xml
	 * @param musicMessage
	 * @return
	 */
	public static String musicMessageToXml(MusicMessage musicMessage){
//		XStream xstream = new XStream();
		xstream.alias("xml", musicMessage.getClass());
		return xstream.toXML(musicMessage);
	}
	/**
	 * 图锟斤拷锟斤拷息锟斤拷锟斤拷�?
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String initNewsMessage(String toUserName,String fromUserName){
		String message = null;
		List<News> newsList = new ArrayList<News>();
		NewsMessage newsMessage = new NewsMessage();
		
		News news = new News();
		news.setTitle("欢迎关注社区微信公众号");
		news.setDescription("请先进行注册，然后用您所注册的帐号登录您的社区平台");
		news.setPicUrl("http://czw.tunnel.qydev.com/FenXiao/img/ppt3808.jpg");
		news.setUrl("http://czw.tunnel.qydev.com/FenXiao/pages/weixin/register.jsp?toUserName="+toUserName);
		
		newsList.add(news);
		
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MESSAGE_NEWS);
		newsMessage.setArticles(newsList);
		newsMessage.setArticleCount(newsList.size());
		
		message = newsMessageToXml(newsMessage);
		
		return message;
	}
	
	/**
	 * 锟斤拷装图片锟斤拷息
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	/*public static String initImageMessage(String toUserName,String fromUserName){
			String message = "";
			String mediaId="Hfarc3trqWLgUiSku-DYvTuO_ygbbppK_c_JRCZm9JOODkKFRU5NgRTJVMyfKXuw";
			Image image = new Image();
			StringBuffer sb = new StringBuffer();
			sb.append("<xml>\n");
			sb.append("<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n");
			sb.append("<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n");
			sb.append("<CreateTime><![CDATA["+new Date().getTime()+"]]></CreateTime>\n");
			sb.append("<MsgType><![CDATA[image]]></MsgType>\n");
			sb.append("<Image>\n");
			sb.append("<MediaId><![CDATA["+mediaId+"]]></MediaId>\n");
			sb.append("</Image>\n");
			sb.append("</xml>");
			message = sb.toString();
			return message;
	}*/
	public static String initImageMessage(String toUserName,String fromUserName){
		String message = null;
		/*Image image = new Image();
		image.setMediaId("yA-B2FwBUaQ5A5KoL9_Xie0SKjEtfGLyLZ2xed2zhZBm9aa6pWhAO5Mt2yCkG8X8");
		ImageMessage imageMessage = new ImageMessage();
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setMsgType(MESSAGE_IMAGE);
		imageMessage.setCreateTime(new Date().getTime());
		imageMessage.setImage(image);
		message = imageMessageToXml(imageMessage);*/
		message = "<xml>"
				+ "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>"
				+ "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>"
				+ "<CreateTime><![CDATA["+new Date().getTime()+"]]></CreateTime>"
				+ "<MsgType><![CDATA[image]]></MsgType>"
				+ "<Image>"
				+ "<MediaId>"
				+ "<![CDATA[yA-B2FwBUaQ5A5KoL9_Xie0SKjEtfGLyLZ2xed2zhZBm9aa6pWhAO5Mt2yCkG8X8]]>"
				+ "</MediaId>"
				+ "</Image>"
				+ "</xml>";
		return message;
	}
	
	public static String initVideoMessage(String toUserName,String fromUserName){
		String message = null;
		
		message = "<xml>\n"
				+ "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n"
				+ "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n"
				+ "<CreateTime><![CDATA["+new Date().getTime()+"]]></CreateTime>\n"
				+ "<MsgType><![CDATA[video]]></MsgType>\n"
				+ "<Video>\n"
				+ "<MediaId>\n"
				+ "<![CDATA[i0xqapKMpHT_SNTQj0wcIcjcGkD7p9oWAe38E9p5mLR0O_p_eA_7mfcN54ByxvR7]]>\n"
				+ "</MediaId>\n"
				/*+"<Title><![CDATA[佟丽娅扎卷发马尾梳空气刘�?清纯似少女]]></Title>"
				+"<Description><![CDATA[我爱佟丽娅]]></Description>"*/
				+ "</Video>\n"
				+ "</xml>";
		return message;
	}
	
	
	
	/*<xml>
	<ToUserName><![CDATA[toUser]]></ToUserName>
	<FromUserName><![CDATA[fromUser]]></FromUserName>
	<CreateTime>12345678</CreateTime>
	<MsgType><![CDATA[video]]></MsgType>
	<Video>
	<MediaId><![CDATA[media_id]]></MediaId>
	<Title><![CDATA[title]]></Title>
	<Description><![CDATA[description]]></Description>
	</Video> 
	</xml>*/
	
	/**
	 * 锟斤拷装锟斤拷锟斤拷锟斤拷息
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String initMusicMessage(String toUserName,String fromUserName){
		String message = null;
		Music music = new Music();
		music.setThumbMediaId("Ks0hJ66cncKyUE1sIxkL3yT2Fe6FTVcBolWBmJw82gqxdXyb2FppI_ad6GDuq2KN");
		music.setTitle("头文字D");
		music.setDescription("BACK ON THE ROCKS");
		music.setMusicUrl("http://czw.tunnel.qydev.com/transport/image/BACK ON THE ROCKS.mp3");
		music.setHQMusicUrl("http://czw.tunnel.qydev.com/transport/image/BACK ON THE ROCKS.mp3");
		
		MusicMessage musicMessage = new MusicMessage();
		musicMessage.setFromUserName(toUserName);
		musicMessage.setToUserName(fromUserName);
		musicMessage.setMsgType(MESSAGE_MUSIC);
		musicMessage.setCreateTime(new Date().getTime());
		musicMessage.setMusic(music);
		message = musicMessageToXml(musicMessage);
		return message;
	}
	
}
